package com.sunxd.zstudy.juc.T20_ThreadPool.threadPool;

import java.util.concurrent.*;

/**
 * @author: 作者名称
 * @date: 2021-09-14 11:26
 **/
public class  T1_MyExecutor_Callable_Executors implements Executor {


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        new T1_MyExecutor_Callable_Executors().execute(() ->{
            System.out.println(0);
        });


        // 不建议用jdk自带的，默认队列长度Integer.MAX_VALUE，导致oom
        ExecutorService e = Executors.newCachedThreadPool();
        // Callable
        Callable<String> callable = new Callable() {
            @Override
            public Object call() throws Exception {
                TimeUnit.SECONDS.sleep(5);
                return "callable : 1";
            }
        };
        Future<String> submit1 = e.submit(callable);
        // get阻塞，直到线程执行结束
        System.out.println(submit1.get());


        Future<Integer> submit = e.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            System.out.println(2);
            return 3;
        });
        System.out.println(submit.get());


        e.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            System.out.println(1);
        });


    }

    @Override
    public void execute(Runnable command) {
        System.out.println(1);
        command.run();
    }
}
